<template>
    <AdminSkeleton>
        <template #header>
            <div class="params-form">
                <el-form :model="paramsForm" label-width="auto">
                    <el-form-item label="年份:" size="small">
                        <el-config-provider>
                            <el-select v-model="paramsForm.jcYear" placeholder="请选择年份" size="small" style="width: 80px"
                                @visible-change="getYears">
                                <el-option v-for="item in yearsArr" :label="item" :value="item" :key="item" />
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="线路:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                            <el-select v-model="paramsForm.lines" clearable placeholder="可留空" size="small"
                                style="width: 110px" multiple collapse-tags collapse-tags-tooltip @change="changeLines"
                                @visible-change="getLines">
                                <template #header>
                                    <el-checkbox v-model="lineCheckAll" :indeterminate="lineIndeterminate"
                                        @change="lineHandleCheckAll">
                                        全选
                                    </el-checkbox>
                                </template>
                                <!-- <el-option label="" :value="''" /> -->
                                <el-option v-for="item in linesAndStationsArr" :label="item.label" :value="item.value"
                                    :key="item.value" />
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="站点:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                            <el-select v-model="paramsForm.stations" multiple clearable collapse-tags
                                collapse-tags-tooltip placeholder="可留空" size="small" style="width: 130px"
                                @change="changeStations">
                                <template #header>
                                    <el-checkbox v-model="stationCheckAll" :indeterminate="stationIndeterminate"
                                        @change="stationHandleCheckAll">
                                        全选
                                    </el-checkbox>
                                </template>
                                <!-- <el-option label="" :value="''" /> -->
                                <el-option v-for="item in stationsArr" :label="item.label" :value="item.value"
                                    :key="item.value" />
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="完成状态:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                            <el-select v-model="paramsForm.isFinish" clearable placeholder="可留空" size="small"
                                style="width: 100px">
                                <el-option v-for="item in isFinishArr" :label="item.label" :value="item.value"
                                    :key="item.value" />
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="单据状态:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                            <el-select v-model="paramsForm.status" clearable placeholder="可留空" size="small"
                                style="width: 100px">
                                <el-option v-for="item in statusArr" :label="item.label" :value="item.value"
                                    :key="item.value" />
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="描述:" size="small">
                        <el-input v-model="paramsForm.description" size="small" style="width: 100px" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="getJcDatas(paramsForm)"
                        :loading = "loading">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>
        <template #control>
            <div class="control-box">
                <div class="person-box">
                    <span class="batchChangeStatus">当前用户：</span>
                    <span class="batchChangeStatus">{{ useStore.userInfo.REALNAME }}</span>
                </div>
                <div class="person-box">
                    <span class="batchChangeStatus">配合人2：</span>
                    <el-input v-model="person2" autocomplete="off" size="small" />
                </div>
                <div class="person-box">
                    <span class="batchChangeStatus">配合人2：</span>
                    <el-input v-model="person3" autocomplete="off" size="small" />
                </div>
                <div class="date-box">
                    <span class="batchChangeStatus">完成日期：</span>
                    <el-date-picker size="small" v-model="newPlanDate" type="date" placeholder="请选择日期"
                        format="YYYY/MM/DD" value-format="YYYY-MM-DD" :value-on-clear="''" />
                </div>
                <div class="btn-box">
                    <el-button type="warning" plain size="small" title="批量通过"
                        @click="editJcData('batchPass', selectJcDatas)">
                        <el-icon>
                            <EditPen />
                        </el-icon><span class="batchChangeStatus">批量通过</span>
                    </el-button>
                    <el-button type="warning" plain size="small" title="提交" class="submit-btn"
                        @click="editSubmit('batchPass', changeDatasArrs)">
                        提交
                    </el-button>
                </div>

            </div>
            <Paging :dataLength="datasLength" :countPage="countPage" :btnDisabledObj="btnDisabledObj"
                v-model:firstPage="firstPage" v-model:pageSize="pageSize" @toNext="nextPage(firstPage)"
                @toLast="lastPage(firstPage)" @toFirst="toFirstPage" @toEnd="toEndPage" @toSpecify="toSpecifyPage"
                @changePsize="changePageSize"></Paging>
        </template>
        <template #content>
            <el-table :data="newDatasArr" style="width: 100%" v-loading="loading"
                @selection-change="handleSelectionChange" id="jcDataTable">
                <el-table-column type="selection" width="50" />
                <el-table-column fixed prop="WONUM" label="WONUM" width="90" />
                <el-table-column fixed prop="DESCRIPTION" label="描述" width="150" />
                <el-table-column prop="AREA" label="作业区域" width="120" />
                <el-table-column prop="AREA2" label="作业区域2" width="120" />
                <el-table-column prop="ISPASS" label="是否通过" width="60">
                    <template #default="{ row }">
                        <el-input v-model="row.ISPASS" autocomplete="off" size="small" />
                    </template>
                </el-table-column>
                <el-table-column prop="FINISHDATE" label="实际完成日期" width="135">
                    <template #default="{ row }">
                        <el-date-picker style="width:7.5rem;" clearable :value-on-clear="''" v-model="row.FINISHDATE"
                            type="date" placeholder="请选择日期" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                            size="small" />
                    </template>
                </el-table-column>
                <el-table-column prop="PERSON" label="配合人" width="80">
                    <template #default="{ row }">
                        <el-input v-model="row.PERSON" autocomplete="off" size="small" />
                    </template>
                </el-table-column>
                <el-table-column prop="PERSON2" label="配合人2" width="80">
                    <template #default="{ row }">
                        <el-input v-model="row.PERSON2" autocomplete="off" size="small" />
                    </template>
                </el-table-column>
                <el-table-column prop="PERSON3" label="配合人3" width="80">
                    <template #default="{ row }">
                        <el-input v-model="row.PERSON3" autocomplete="off" size="small" />
                    </template>
                </el-table-column>
                <el-table-column prop="REMARK" label="备注" width="120">
                    <template #default="{ row }">
                        <el-input v-model="row.REMARK" autocomplete="off" size="small" type="textarea" autosize />
                    </template>
                </el-table-column>
                <el-table-column prop="CUST_LINENUM" label="线路" width="60" />
                <el-table-column prop="CUST_SPECNUM" label="专业" width="60" />
                <el-table-column prop="SPEC_DESC" label="专业名称" width="60" />
                <el-table-column prop="CUST_SUBSYS" label="子系统" width="80" />
                <el-table-column prop="SUB_DESC" label="子系统名称" width="120" />
                <el-table-column prop="LOCATION" label="站点" width="80" />
                <el-table-column prop="PERSONGROUP" label="作业工班" width="120" />
                <el-table-column prop="PGNAME" label="班组名称" width="130" />
                <el-table-column prop="SCHEDFINISH" label="计划完成日期" width="120">
                    <template #default="{ row }">
                        {{ dateFormat(row.SCHEDFINISH) }}
                    </template>
                </el-table-column>
                <el-table-column prop="DEVICENUM" label="设备编号" width="170" />
                <el-table-column prop="SBDESC" label="现场设备描述" width="150" />
                <el-table-column prop="STATUS" label="状态" width="60" />
            </el-table>
        </template>
    </AdminSkeleton>
</template>

<script setup>
import { ref, reactive } from 'vue'
import AdminSkeleton from '@/components/AdminSkeleton.vue'
import Paging from '@/components/Paging.vue'
import { getLinesInfo } from '@/utils/xfjcApi/device'
import { getJcDataWriteInfo, batchJcDataWrite } from '@/utils/xfjcApi/jcDataWrite'
import { xfjcStore } from '@/stores/jcStore'
import { mainStore } from '@/stores/store'
import { dateFormat } from '@/utils/dateFormat'
import { msgOpen } from '@/utils/msg'
import { paging } from '@/utils/paging'

let useJcStore = xfjcStore()
let useStore = mainStore()

const {
    datasArr,
    datasLength,
    firstPage,
    pageSize,
    countPage,
    newDatasArr,
    btnDisabledObj,
    pagingPreprocessing,
    nextPage,
    lastPage,
    toFirstPage,
    toEndPage,
    toSpecifyPage,
    changePageSize
} = paging() //分页

//参数
//#region 
/********************************************************************************************************************* */
let yearsArr = ref([])
//线路、站点
let linesAndStationsArr = ref([])
let lineCheckAll = ref(false)
let lineIndeterminate = ref(false) //设置不确定状态，仅负责样式控制
let stationsArr = ref([])
let stationCheckAll = ref(false)
let stationIndeterminate = ref(false)

//完成状态
let isFinishArr = ref([
    { label: '未完成', value: 0 },
    { label: '已完成', value: 1 }
])

//单据状态
let statusArr = ref([
    { label: '不使用', value: 0 },
    { label: '在用', value: 1 }
])

let paramsForm = reactive({
    jcYear: '',
    lines: [],
    stations: [],
    isFinish: '',
    status: '',
    description: '',
    subsys: ['FASFGB','FASQSB','FASQGX','FASQXF'] //固定值
})
let loading = ref(false)
let jcDatasArr = ref([])


//年份
const getYears = () => {
    let fullYear = new Date().getFullYear()
    let arr = []
    for (let i = 2020; i <= fullYear; i++) {
        arr.push(i)
    }
    yearsArr.value = arr
    // console.log(yearsArr.value)
}

/**
* location转换为树形
* @param {Array} arr workType 原数组对象 
*/
const locationToTree = (arr) => {
    let line = []
    // 先把线路拿出来
    arr.forEach(item => {
        if (item.AREATYPE === '线路') {
            let lineObj = {
                label: item.DESCRIPTION,
                value: item.LOCATION,
                children: []
            }
            line.push(lineObj)
        }
    })
    // 再把站点拿出来
    line.forEach(item => {
        arr.forEach(item1 => {
            if (item.value === item1.CUST_LINENUM && item1.AREATYPE !== '线路') {
                let stationObj = {
                    label: item1.DESCRIPTION,
                    value: item1.LOCATION,
                    parent: item.value
                }
                item.children.push(stationObj)
            }
        })
    })
    // console.log(line)
    return line
}

//获取线路站点数据
const getLines = async () => {
    //获取数据
    if (!useJcStore.linesInfo.length) {
        let lines = await getLinesInfo()
        if (lines.status) {
            linesAndStationsArr.value = locationToTree(lines.resDatas.lines)
            useJcStore.setLinesInfo(linesAndStationsArr.value)
        }
    } else {
        linesAndStationsArr.value = useJcStore.linesInfo
    }
}

/**
* 改变线路联动站点
* @param val 选中的线路值
*/
const changeLines = (val) => {
    // console.log(val)
    // console.log(typeof val)
    // console.log(Array.isArray(val))    
    //#region  
    //单选   
    if (typeof val === 'string') {
        linesAndStationsArr.value.forEach(item => {
            // console.log(item)            
            if (item.value === val) stationsArr.value = item.children
        })
    }
    //多选 el-select组件多选后使用typeof判断为object，需要使用Array.isArray()才能判断为数组
    if (Array.isArray(val)) {
        //每次改变线路时，都要把站点清空
        paramsForm.stations = []
        stationCheckAll.value = false
        stationIndeterminate.value = false
        if (val.length === 1) {
            //取消全选
            if (linesAndStationsArr.value.length && val.length !== linesAndStationsArr.value.length) {
                lineCheckAll.value = false
                lineIndeterminate.value = true
            }
            linesAndStationsArr.value.forEach(item => {
                // console.log(item)            
                if (item.value === val[0]) stationsArr.value = item.children
            })
        }
        else if (val.length === 0) {
            stationsArr.value = []
            stationCheckAll.value = false
            stationIndeterminate.value = false
            lineCheckAll.value = false
            lineIndeterminate.value = false
        }
        else if (val.length > 1) {
            // 当val长度大于1切等于线路数组长度时，全选勾选
            if (val.length === linesAndStationsArr.value.length) {
                lineCheckAll.value = true
                lineIndeterminate.value = false
            } else {
                lineCheckAll.value = false
                lineIndeterminate.value = true
            }
            let staArrss = []
            // 当val长度大于1时，获取站点
            for (let i = 0; i < val.length; i++) {
                let staArrs = []
                for (let j = 0; j < linesAndStationsArr.value.length; j++) {
                    let staArr = []
                    if (linesAndStationsArr.value[j].value === val[i]) {
                        staArr.push(...linesAndStationsArr.value[j].children)
                        staArrs.push(...staArr)
                    }
                }
                staArrss.push(...staArrs)
            }
            stationsArr.value = staArrss
        }
    }
    //#endregion
}

//线路全选
const lineHandleCheckAll = (val) => {
    lineIndeterminate.value = false
    if (val) {
        paramsForm.lines = linesAndStationsArr.value.map((_) => _.value)
        //需要调用changeLines方法，否则会出现选中的线路没有站点的情况
        changeLines(paramsForm.lines)
    } else {
        paramsForm.lines = []
        //需要调用changeLines方法，否则会出现不选线路后站点仍存在的情况
        changeLines(paramsForm.lines)
    }
}

/**
* 站点变更
* @param val 选中的站点值
*/
const changeStations = (val) => {
    if (Array.isArray(val)) {
        if (val.length === 1) {
            //取消全选
            if (stationsArr.value.length && val.length !== stationsArr.value.length) {
                stationCheckAll.value = false
                stationIndeterminate.value = true
            }
        }
        else if (val.length === 0) {
            stationCheckAll.value = false
            stationIndeterminate.value = false
        }
        else if (val.length > 1) {
            // 当val长度大于1切等于站点数组长度时，全选勾选
            if (val.length === stationsArr.value.length) {
                stationCheckAll.value = true
                stationIndeterminate.value = false
            } else {
                stationCheckAll.value = false
                stationIndeterminate.value = true
            }
        }
    }
}

/**
* 站点全选
* @param val 站点全选值
*/
const stationHandleCheckAll = (val) => {
    stationIndeterminate.value = false
    if (val) {
        paramsForm.stations = stationsArr.value.map((_) => _.value)
    } else {
        paramsForm.stations = []
    }
}

/**
* 获取检测数据
* @param {Object} form 表单参数对象
*/
const getJcDatas = async (form) => {
    if (form.jcYear === "") {
        msgOpen("请选择检测年份")
    } else {
        loading.value = true
        let res = await getJcDataWriteInfo(form)
        // console.log(res)
        pagingPreprocessing(res.resDatas.jcDataInfo) //分页前置处理
        // jcDatasArr.value = res.resDatas.jcDataInfo 
        loading.value = false
    }
}
/************************************************************************************************************ */
//#endregion

//批量填报检测记录
//#region 
/***************************************************************************************************************************** */
let submitType = ref('')//提交类型
let person2 = ref("") //人员2
let person3 = ref("") //人员3
let newPlanDate = ref("")   //须要填报的完成日期
let remark = ref("") //备注
let selectJcDatas = ref([]) //选中的检测记录行数据
let changeDatasArrs = [] //用于存储批量修改的数据

newPlanDate.value = dateFormat(new Date())

/**
* 处理单个设备编辑、删除
* @param type 操作类型
* @param row 选中的设备行数据
*/
const editJcData = async (type, row) => {
    // console.log(type)
    // console.log(row)
    // console.log(person2.value +"--"+ person3.value +"--"+ newPlanDate.value)    
    submitType.value = type
    if (type === "batchPass") {
        if (!row.length) {
            msgOpen("请选择需要处理的检测记录")
        } else {
            row.forEach(item => {
                let obj = {
                    ISPASS: "通过",
                    FINISHDATE: newPlanDate.value,
                    PERSON: useStore.userInfo.REALNAME,
                    PERSON2: person2.value,
                    PERSON3: person3.value,
                    REMARK: remark.value,
                    WONUM: item.WONUM,
                }
                item.ISPASS = "通过"
                item.FINISHDATE = newPlanDate.value
                item.PERSON = useStore.userInfo.REALNAME
                item.PERSON2 = person2.value
                item.PERSON3 = person3.value
                item.REMARK = remark.value
                changeDatasArrs.push(obj)
            })
            console.log(changeDatasArrs)
        }
    }
}

/**
* 表格选中行数据变化时触发的方法
* @param val 选中的设备行数据
*/
const handleSelectionChange = (val) => {
    selectJcDatas.value = val
}

/******************************************************************************************************************************** */
//#endregion

/**
* 提交处理
* @param type 处理类型
* @param data 处理数据
*/
const editSubmit = async (type, data) => {
    // console.log(type)
    // console.log(data)
    if (type === 'batchPass') {
        if (!data.length) {
            msgOpen("请选择提交的检测记录")
        } else {
            let res = await batchJcDataWrite(type, data)
            // console.log(res)
            changeDatasArrs = []
            res.status ? msgOpen(res.msg, 'success') : msgOpen(res.msg)
            getJcDatas(paramsForm)
        }
    }
}

</script>

<style lang="less" scoped>
.params-form {
    height: 100%;
    width: 100%;

    .el-form {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: space-around;

        .el-form-item {
            margin-bottom: 0;
            margin-right: .1875rem;
        }
    }
}

.el-table {
    height: 95%;

}



.submit-btn {
    margin-left: .625rem;
}

.control-box {
    width: 55%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .person-box {
        width: 19%;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .batchChangeStatus {
            width: 45%;
            font-size: .625rem;
            margin-left: .625rem;
        }

        .el-input {
            width: 55%
        }
    }

    .date-box {
        width: 28%;
        display: flex;
        align-items: center;

        .batchChangeStatus {
            width: 50%;
            font-size: .625rem;
            margin-left: .625rem;
        }
    }

    .btn-box {
        width: 15%;
        display: flex;
        align-items: center;
        justify-content: space-around;
    }
}
</style>